package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprService empExprService;

    /**
     * 条件分页查询
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<Emp> getPageResult(EmpQueryParam param) {

        //构建分页对象
        Page<Emp> p = new Page<>(param.getPage(),param.getPageSize());
       /* //构建查询条件
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(param.getName() != null && !param.getName().isEmpty(),Emp::getName,param.getName())
                .eq(param.getGender() != null ,Emp::getGender,param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null ,Emp::getEntryDate,param.getBegin(),param.getEnd());
        //调用page方法
        p = page(p,queryWrapper);*/
        p.addOrder(OrderItem.desc("update_time"));

        //调用 lambdaQuery（）
        p = lambdaQuery().like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd())
                .page(p);

        //获取员工集合
        List<Emp> emps = p.getRecords();

        //遍历员工部门id，获取员工部门id
        List<Long> deotId = emps.stream().map(emp -> emp.getDeptId()).collect(Collectors.toList());

        if(!deotId.isEmpty()){
            // 调用deptservice方法，批量查询部门信息
            List<Dept> depts = deptService.listByIds(deotId);
            //将部门名称封装到员工对象中
            emps.forEach(emp -> {
                depts.forEach(dept -> {
                    if (emp.getDeptId() != null && emp.getDeptId().equals(dept.getId())){
                        emp.setDeptName(dept.getName());
                    }
                });
            });

        }

        //返回分页结果
        return new PageResult<>(p.getTotal(),emps);
    }

    /**
     * 新增员工
     * @param emp
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveEmp(Emp emp) {
        //保存员工基本信息
        //补全基础代码
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        save(emp);

        //保存员工的工作经历信息

        List<EmpExpr> exprList = emp.getExprList();
        //遍历工作经历
        if(!exprList.isEmpty()){
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        }
        empExprService.saveBatch(exprList);


    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Transactional(noRollbackFor = Exception.class)
    @Override
    public void removeEmp(List<Integer> ids) {
        //调用service 方法删除员工信息
        removeBatchByIds(ids);

        //调用EmpExprService方法批量删除员工的工作经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId,ids));
    }

    /**
     * 根据id回显信息
     * @param id
     * @return
     */
    @Override
    public Emp getEmpById(Integer id) {
        //获取员工的id
        Emp emp = getById(id);

        //获取员工的工作经历
        emp.setExprList(empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId,id)));
        return emp;
    }

    /**
     * 修改员工信息
     *
     * @param emp
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateEmp(Emp emp) {
        //修改员工信息
        //补全基础代码
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);

        //批量删除员工工作经历信息
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId,emp.getId()));

        //批量保存员工信息
        List<EmpExpr> exprList = emp.getExprList();
        if(exprList != null && !exprList.isEmpty()){
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        }
        empExprService.saveBatch(exprList);


    }
}
